package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.service.IBaseService;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.domain.Department;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;

import javax.annotation.Resource;
import java.util.List;

public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery> implements IBaseService<T,Q> {

    @Autowired
    private Mapper<T> mapper;
    @Override
    public List<T> findAll() {
        return mapper.selectAll();
    }

    @Override
    public PageList<T> findPage(Q q) {
        // 创建高级查询对象

        // 设置分页
        PageHelper.startPage(q.getPage(),q.getSize());
        // 查询数据
        List<T> page = mapper.selectAll();
        // 封装对象
        PageInfo<T> pageInfo = new PageInfo<>(page);
        // 封装到自定义的对象中并返回
        return new PageList<>(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public T findOne(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(T t) {
        if (t.getId() == null){
            mapper.insertSelective(t);
        } else{
            mapper.updateByPrimaryKeySelective(t);
        }

    }

    @Override
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void batchRemove(Q q) {
        //1.获取到所有的ids
        Long[] ids = q.getIds();
        if (ids == null || ids.length == 0){
            return;
        }
        //2.遍历
        for (Long id : ids) {
            mapper.deleteByPrimaryKey(id);
        }
    }
}
